package cn.xawl.gulimall.member.service.impl;

import cn.xawl.common.constant.MemberConstant;
import cn.xawl.common.utils.HttpUtils;
import cn.xawl.gulimall.member.dao.MemberLevelDao;
import cn.xawl.gulimall.member.exception.InvalidPasswordException;
import cn.xawl.gulimall.member.exception.MemberNotExistException;
import cn.xawl.gulimall.member.exception.PhoneNumNotUniqueException;
import cn.xawl.gulimall.member.exception.UsernameNotUniqueException;
import cn.xawl.gulimall.member.service.MemberLevelService;
import cn.xawl.gulimall.member.vo.MemberLoginVo;
import cn.xawl.gulimall.member.vo.MemberVo;
import cn.xawl.gulimall.member.vo.WeiboMemberVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.xawl.common.utils.PageUtils;
import cn.xawl.common.utils.Query;

import cn.xawl.gulimall.member.dao.MemberDao;
import cn.xawl.gulimall.member.entity.MemberEntity;
import cn.xawl.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registerMember(MemberVo member) {
        MemberEntity memberEntity = new MemberEntity();

        //设置会员的基本信息
        memberEntity.setCreateTime(new Date());
        //电话号和会员名不能重复
        checkPhoneNumUnique(member.getTelephone());
        memberEntity.setMobile(member.getTelephone());

        checkUsernameUnique(member.getUsername());
        memberEntity.setUsername(member.getUsername());

        //设置默认的会员等级
        Long defaultLevelId = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(defaultLevelId);

        //设置密码，保存时需要加密处理
        //使用Spring自带的
        String encodePassword = passwordEncoder.encode(member.getPassword());
        memberEntity.setPassword(encodePassword);
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameNotUniqueException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameNotUniqueException();
        }
    }

    @Override
    public void checkPhoneNumUnique(String phone) throws UsernameNotUniqueException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneNumNotUniqueException();
        }
    }

    @Override
    public MemberEntity memberLogin(MemberLoginVo memberLogin) {
        String account = memberLogin.getAccount();
        String password = memberLogin.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", account).or().eq("mobile", account));
        if (memberEntity != null) {
            //如果数据库中有用户信息，判断密码是否正确
            if (!passwordEncoder.matches(password, memberEntity.getPassword())) {
                throw new InvalidPasswordException();
            }
            return memberEntity;
        } else {
            //抛出用户不存在异常
            throw new MemberNotExistException();
        }
    }

    @Override
    public MemberEntity weiboMemberLoginOrRegister(WeiboMemberVo weiboMember) {
        String uid = weiboMember.getUid();
        //根据uid查询当前微博用户是否登陆过，未查到信息代表未登陆过
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (memberEntity != null) {
            //当前用户登陆过，将微博用户信息更新
            memberEntity.setAccessToken(weiboMember.getAccessToken());
            memberEntity.setExpiresIn(weiboMember.getExpiresIn());
            baseMapper.updateById(memberEntity);
            return memberEntity;
        }
        //当前微博用户未登陆过，将该用户注册为本站用户
        MemberEntity newWeiboMember = new MemberEntity();
        newWeiboMember.setUid(uid);
        newWeiboMember.setSourceType(MemberConstant.MemberSourceTypeEnum.WEIBO_USER.getType());
        newWeiboMember.setAccessToken(weiboMember.getAccessToken());
        newWeiboMember.setExpiresIn(weiboMember.getExpiresIn());
        newWeiboMember.setCreateTime(new Date());

        //其他用户的基本信息，根据access token调用微博接口查询。
        //https://api.weibo.com/2/users/show.json?access_token&uid&screen_name
        HttpResponse response = null;
        try {
            Map<String, String> query = new HashMap<>();
            query.put("access_token", weiboMember.getAccessToken());
            query.put("uid", uid);
            response = HttpUtils.doGet("https://api.weibo.com",
                    "/2/users/show.json",
                    "get",
                    new HashMap<>(),
                    query);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            //成功响应数据，获取数据
            try {
                String responseJson = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(responseJson);//根据JSONObject对象可以获取指定JSON字符串key值的value值

                String name = jsonObject.getString("name"); //友好显示名称

                String gender = jsonObject.getString("gender");//性别，m：男、f：女、n：未知

                String header = jsonObject.getString("avatar_large"); //用户头像地址（大图），180×180像素

                String city = jsonObject.getString("location"); //用户所在地

                newWeiboMember.setUsername(name);
                newWeiboMember.setGender("m".equals(gender) ? MemberConstant.MemberGenderEnum.MAN.getGender() : MemberConstant.MemberGenderEnum.WOMEN.getGender());
                newWeiboMember.setHeader(header);
                newWeiboMember.setCity(city);

            } catch (IOException e) {
                e.printStackTrace();
            }
            baseMapper.insert(newWeiboMember);

        }
        return baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
    }


}